/*
 思路还是挺简单的，如果是目录就递归查找，如果是文件就对比是不是要找的
 确定是目录还是文件可以用fstat
 */
#include "kernel/types.h"
#include "kernel/fcntl.h"
#include "kernel/fs.h"
#include "kernel/stat.h"
#include "user/user.h"

char* get(char* path){
    char* p=0;
    for(p=path+strlen(path);p>=path&&*p!='/';p--);
    p++;
    return p;
}

void find(char* cur_path,char* target){
    char buf[512];
    struct dirent de; //目录结构体
    struct stat st;   //文件结构体
    int fd=open(cur_path,0);
    if(fd<0){
        fprintf(2,"find: cannot open %s\n",cur_path);
        return;
    }

    if(fstat(fd,&st)<0){
        fprintf(2,"find: cannot stat %s\n",cur_path);
        close(fd);
        return;
    }

    switch(st.type){
        case T_FILE:
            if(!strcmp(target,get(cur_path)))
                printf("%s\n",cur_path);
            break;
        
        case T_DIR:
            strcpy(buf,cur_path);
            char* p=buf+strlen(buf);
            *p='/';
            p++;
            while(read(fd,&de,sizeof de)==sizeof de){
                if(de.inum==0)
                    continue;
                memmove(p,de.name,DIRSIZ);
                p[DIRSIZ]=0;
                if(stat(buf,&st)<0){
                    printf("ls:cannot stat %s\n",buf);
                    continue;
                }
                if(st.type==T_FILE){
                    if(!strcmp(target,get(buf)))
                        printf("%s\n",buf);
                }
                else if(st.type==T_DIR&&strcmp(".",get(buf))&&strcmp("..",get(buf)))
                    find(buf,target);

            }
            break;
    }        
    close(fd);
    return;         
}

int main(int argc,char* argv[]){
    if(argc==3)
        find(argv[1],argv[2]);
    else{
        fprintf(2,"usage:find [directory] [target]\n");
        exit(1);
    }
    exit(0);
}